package com.pingao.mp.handle;

import com.pingao.mp.modular.sys.entity.Log;
import com.pingao.mp.modular.sys.entity.User;
import com.pingao.mp.utils.Constant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

public class LogHandlerInterceptor implements HandlerInterceptor {

    private final static Logger LOGGER = LoggerFactory.getLogger(LogHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Log log = new Log();
        log.setCreateTime(LocalDateTime.now());
        log.setMethod(request.getMethod());
        log.setServletPath(request.getServletPath());
        log.setQueryString(request.getQueryString());
        log.setRemoteHost(request.getRemoteHost());
        log.setRemoteAddr(request.getRemoteAddr());
        HandlerMethod detailHandlerMethod = (HandlerMethod) handler;
        MethodParameter[] methodParameters = detailHandlerMethod.getMethodParameters();
        StringBuilder requestPar = new StringBuilder();
        if (methodParameters.length > 0) {
            for (MethodParameter methodParameter : methodParameters) {
                if (methodParameter.getParameterName() == null) continue;
                requestPar.append(methodParameter.getParameterName()).append("-->").append("、");
            }
        }
        log.setRequestParams(requestPar.length() > 0 ? requestPar.substring(0, requestPar.length() - 1) : requestPar.toString());
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser != null) {
            Session session = currentUser.getSession();
            Object user = session.getAttribute(Constant.LoginUser);
            if (user != null) {
                User u = (User) user;
                log.setUserId(u.getId());
            }
        }
        log.insertOrUpdate();
        return true;
    }
}